use std::sync::atomic::Ordering;
use serde::{Deserialize, Serialize};
use crate::front::shelf_service::{get_shelf_list, ShelfListReq,modify_shelf_monitor,ShelfMonitorReq};
use crate::front::shelf_statistics_service::get_shelf_statistics;
use crate::utils::js_bridge::{get_callbacks, JsResult};
use crate::TaskManager;
//use crate::example;
use crate::service::execute_service;
use crate::utils::ajax_result::AjaxResult;
use crate::utils::page_result::PageResult;

#[tauri::command]
pub async fn js_initialized() {
    log::info!("【主程序】JS已初始化");
    // JS已初始化，现在可以安全调用
    // example::test();
    execute_service::execute();
}

#[tauri::command]
pub async fn shelf_list(data: ShelfListReq) -> PageResult<crate::entity::account_info::Model> {
    log::info!("【主程序】收到来自 GUI 的货架列表命令:{:?}",data);
    if data.syn_zh.is_some() && (data.syn_zh.as_ref().unwrap()=="1" || data.syn_zh.as_ref().unwrap()=="2"){
        let flag=if data.syn_zh.as_ref().unwrap()=="2" {1} else {0};
        let _ = crate::service::syn_zh_service::syn_zh_with_time_update(flag).await;
    }
    get_shelf_list( data).await
}

#[tauri::command]
pub async fn shelf_monitor(data: ShelfMonitorReq) -> AjaxResult<()> {
    log::info!("【主程序】收到来自 GUI 的货架修改命令:{:?}",data);
    modify_shelf_monitor(data).await
}

#[tauri::command]
pub async fn shelf_statistics() -> AjaxResult<crate::front::shelf_statistics_service::ShelfStatistics> {
    log::info!("【主程序】收到来自 GUI 的货架统计命令");
    get_shelf_statistics().await
}

/**
 * 停止后台任务
 */
#[tauri::command]
pub fn stop_background_tasks() {
    log::info!("【主程序】收到来自 GUI 的停止命令");
    let manager = TaskManager::global();
    manager.running.store(false, Ordering::SeqCst);
}

/**
 * JS 回调处理
 */
#[tauri::command]
pub fn js_callback(data: serde_json::Value) {
    log::info!("收到 JS 回调命令: {:?}", data);

    let callback_id = data["callback_id"].as_str().unwrap_or("");
    let result = data["result"].as_str().map(|s| s.to_string());
    let error = data["error"].as_str().map(|s| s.to_string());

    let callbacks = get_callbacks();
    let mut callbacks = callbacks.lock().unwrap();

    if let Some(tx) = callbacks.remove(callback_id) {
        let js_result = match (result, error) {
            (Some(result), _) => JsResult::Success(result),
            (_, Some(error)) => JsResult::Error(error),
            _ => JsResult::Error("Invalid callback data".into()),
        };

        log::info!("发送回调结果: {:?}", js_result);
        let _ = tx.send(js_result);
    } else {
        log::info!("未找到匹配的回调 ID: {}", callback_id);
    }
}

/**
 * 测试 greet
 */
#[tauri::command]
pub fn greet(message: &str) -> MyStruct {
    let msg =format!("你好，{}！这是 Rust 代码返回的消息。", message);
    log::info!("【执行rust】成功完成,结果:{}",msg);
    return MyStruct {
        name: msg,
        age: 28,
    };
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MyStruct {
    pub name: String,
    pub age: i64,
}
